package cc.ipost.ipost;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import cc.ipost.ipost.data.RequestData;

@SuppressLint("HandlerLeak")
public class AddressListActivity extends Activity {
	ListView list;
	ArrayList<HashMap<String, Object>> listItem;
	SimpleAdapter listItemAdapter;
	ProgressDialog loadingDialog;
	boolean forResult;

	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.address_list);
		list = (ListView) findViewById(R.id.address_list);
		listItem = new ArrayList<HashMap<String, Object>>();
		loadingDialog = new ProgressDialog(this);
		loadingDialog.setMessage("Loading....");

		Intent i = this.getIntent();
		forResult = i.getBooleanExtra("forResult", false);

		View homebtn = this.findViewById(R.id.navhome_btn);
		if (forResult) {
			ImageView navicon = (ImageView) findViewById(R.id.nav_btn_icon);
			navicon.setImageResource(R.drawable.undo_icon);
			homebtn.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					Intent i = new Intent();
					AddressListActivity.this.setResult(RESULT_CANCELED, i);
					AddressListActivity.this.finish();
				}
			});

		} else {
			homebtn.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					Intent in = new Intent(AddressListActivity.this,
							MainActivity.class);
					AddressListActivity.this.startActivity(in);

				}
			});
		}

		View plusBtn = findViewById(R.id.plus_btn);
		plusBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(AddressListActivity.this,
						AddressActivity.class);
				startActivityForResult(i, 0);
			}
		});
		updateInfo();

	}

	private void updateInfo() {
		MyApplication ma = (MyApplication) this.getApplication();
		if (ma.user == null) {
			Intent i = new Intent(this, AccountActivity.class);
			this.startActivity(i);
		}
		loadingDialog.show();
		RequestData rd = new RequestData(String.format(MySettings.UCONTACT,
				ma.user.ID), RequestData.GET);

		WebServiceTask wst = new WebServiceTask(rd, handler);
		wst.execute("");
	}

	protected Handler delHandler = new Handler() {

		public void handleMessage(Message msg) {
			loadingDialog.dismiss();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("del card fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(AddressListActivity.this)
						.setMessage(msgs).setNegativeButton("OK", null)
						.setCancelable(true).show();
				break;
			}
			case MySettings.ERR: {
				Log.e("del card err", msg.toString());
				new AlertDialog.Builder(AddressListActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("del card success", msg.toString());
				updateInfo();
			}
			}
		}
	};

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.dismiss();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("get contacts info fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(AddressListActivity.this)
						.setMessage(msgs).setNegativeButton("OK", null)
						.setCancelable(true).show();
				break;
			}
			case MySettings.ERR: {
				Log.e("get contacts info err", msg.toString());
				new AlertDialog.Builder(AddressListActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("get contacts info success", msg.toString());
				try {
					JSONArray contacts = ((JSONObject) msg.obj)
							.getJSONArray("contacts");
					initListView(contacts);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println(msg.obj);
			}
			}

		}
	};

	private void initListView(JSONArray contacts) throws JSONException {
		this.listItem.clear();
		for (int i = 0; i < contacts.length(); i++) {
			JSONObject contact = contacts.getJSONObject(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", contact.getString("fname"));
			map.put("id", contact.getString("id"));
			map.put("loc", contact.getString("location"));
			map.put("zipcode", contact.getString("zipcode"));
			this.listItem.add(map);
		}
		// 生成适配器的Item和动态数组对应的元素
		listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
				R.layout.address_item,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "name", "zipcode", "loc" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.receiver_name, R.id.receiver_zipcode, R.id.receiver_address });

		list.setAdapter(listItemAdapter);

		if (forResult) {

			list.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					Intent i = new Intent();
					i.putExtras(configContactBundle(arg2));
					AddressListActivity.this.setResult(RESULT_OK, i);
					AddressListActivity.this.finish();
				}
			});
		}
		list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle(getString(R.string.action));
				menu.add(0, 0, 0, getString(R.string.delete));
				menu.add(0, 1, 0, getString(R.string.edit));
			}
		});
	}

	@SuppressWarnings("rawtypes")
	private Bundle configContactBundle(int position) {
		HashMap cm = (HashMap) listItemAdapter.getItem(position);
		Bundle b = new Bundle();
		b.putString("id", cm.get("id").toString());
		b.putString("name", cm.get("name").toString());
		b.putString("location", cm.get("loc").toString());
		b.putString("zipcode", cm.get("zipcode").toString());
		return b;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		if (item.getItemId() == 0) {
			HashMap cm = (HashMap) listItemAdapter.getItem(menuInfo.position);
			String cid = cm.get("id").toString();
			RequestData rd = new RequestData(String.format(MySettings.CONTACT,
					cid), RequestData.DELETE);
			WebServiceTask wst = new WebServiceTask(rd, delHandler);
			wst.execute("");
		} else if (item.getItemId() == 1) {
			Intent i = new Intent(AddressListActivity.this,
					AddressActivity.class);
			i.putExtras(configContactBundle(menuInfo.position));
			startActivityForResult(i, 0);
		}
		return super.onContextItemSelected(item);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// super.onActivityResult(requestCode, resultCode, data);
		System.out.println("resultCode: " + resultCode);
		System.out.println("requestCode: " + requestCode);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 0: {
				if (forResult) {
					Intent i = new Intent();
					Bundle b = data.getExtras();
					if (b != null) {
						i.putExtras(b);
						AddressListActivity.this.setResult(RESULT_OK, i);
						AddressListActivity.this.finish();
					}
				} else {
					updateInfo();
				}
			}
				break;
			default:
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

}
